part of '../repository.dart';

const _kCustomCollectionFolderDataIdKey = 'id';
const _kCustomCollectionFolderDataTitleKey = 'title';
const _kCustomCollectionFolderDataCollectionDataListKey = 'collections';

const _kCustomCollectionFolderTypeValue = 'custom_collection_folder';

class _CustomCollectionFolderDataDto extends Equatable implements _CustomCollectionListItemDataDto {
  const _CustomCollectionFolderDataDto._internal({
    required this.id,
    required this.title,
    required this.collectionDataDtos,
  });

  final String id;
  final String title;
  final BuiltList<_CustomCollectionDataDto> collectionDataDtos;

  @override
  String get type => _kCustomCollectionFolderTypeValue;

  @override
  List<Object?> get props {
    return [
      id,
      title,
      collectionDataDtos,
    ];
  }

  factory _CustomCollectionFolderDataDto.fromJson(Map<String, dynamic> json) {
    final collectionMaps =
        List.castFrom<dynamic, Map>(json[_kCustomCollectionFolderDataCollectionDataListKey]);

    final collectionDtos = collectionMaps.map((collectionMap) {
      final collectionJson = Map.castFrom<dynamic, dynamic, String, dynamic>(collectionMap);
      return _CustomCollectionDataDto.fromJson(collectionJson);
    }).toBuiltList();

    return _CustomCollectionFolderDataDto._internal(
      id: json[_kCustomCollectionFolderDataIdKey],
      title: json[_kCustomCollectionFolderDataTitleKey],
      collectionDataDtos: collectionDtos,
    );
  }

  factory _CustomCollectionFolderDataDto.fromEntity(
      BackupCustomCollectionFolderData collectionFolderData) {
    final collectionDtos = collectionFolderData.collectionDataList.map((collection) {
      return _CustomCollectionDataDto.fromEntity(collection);
    }).toBuiltList();

    return _CustomCollectionFolderDataDto._internal(
      id: collectionFolderData.id,
      title: collectionFolderData.title,
      collectionDataDtos: collectionDtos,
    );
  }

  @override
  Map<String, dynamic> toJson() {
    final collectionDataJsons = collectionDataDtos.map((collectionDataDto) {
      return collectionDataDto.toJson();
    }).toList();

    return {
      _kCustomLexicalItemTypeKey: type,
      _kCustomCollectionFolderDataIdKey: id,
      _kCustomCollectionFolderDataTitleKey: title,
      _kCustomCollectionFolderDataCollectionDataListKey: collectionDataJsons,
    };
  }

  @override
  BackupCustomCollectionFolderData toEntity() {
    final collectionDataList = collectionDataDtos.map((collectionDataDto) {
      return collectionDataDto.toEntity();
    }).toBuiltList();

    return BackupCustomCollectionFolderData(
      id: id,
      title: title,
      collectionDataList: collectionDataList,
    );
  }
}
